import { defineStore } from 'pinia';
import type { AddressInfo, CartItem } from '@/types';
import Decimal from 'decimal.js';
interface SwiperParams {
    goodsId?: string;
    categoryId?: string;
}
export const useStore = defineStore("main", {
    state: () => ({
        cartItems: [] as CartItem[],
        swiperParams: {} as SwiperParams,
        deliveryType: 0,
        selectedAddress:{} as AddressInfo
    }),
    getters: {
        cartTotalPrice(): number {
            return this.cartItems.reduce((a, b) => a + Number(b.totalPrice), 0);
        },
        cartTotalQuantity(): number {
            return this.cartItems.reduce((a, b) => a + b.quantity, 0);
        }
    },
    actions: {
        addTocart(item: CartItem) {
            // 重复
            const isExist = this.cartItems.find(cartItem => cartItem.attrId === item.attrId && cartItem.goodsId === item.goodsId);

            if (isExist) {
                isExist.quantity += item.quantity;
                isExist.totalPrice = new Decimal(isExist.price).times(new Decimal(isExist.quantity));
            } else {
                // 不是无规格商品
                if (item.sid?.length) {
                    this.cartItems.push(item);
                } else {
                    //无规格商品次重复直接更新数量和价格
                    const isNoSpecsExist = this.cartItems.find(cartItem => cartItem.goodsId === item.goodsId);

                    if (isNoSpecsExist) {
                        isNoSpecsExist.quantity += item.quantity;
                    } else {
                        this.cartItems.push(item);
                    }
                }
            }
        }
    }
});